package com.autoagent.ai_live_master.scriptGeneration.service.impl;

import com.autoagent.ai_live_master.common.model.Payload;
import com.autoagent.ai_live_master.common.utils.AgentClient;
import com.autoagent.ai_live_master.scriptGeneration.dto.ProductDesc;
import com.autoagent.ai_live_master.scriptGeneration.dto.ScriptFragmentsDTO;
import com.autoagent.ai_live_master.scriptGeneration.service.ScriptFragmentsService;
import com.autoagent.ai_live_master.scriptGeneration.utils.FusionDataBuilder;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ScriptFragmentsServiceImpl implements ScriptFragmentsService {

    @Autowired
    @Qualifier("fragmentAgentClient")
    private AgentClient agentClient;

    @Autowired
    private FusionDataBuilder fusionDataBuilder;

    @Override
    public String generateScriptFragments(ScriptFragmentsDTO dto) {
        log.info("开始生成片段话术内容 - 用户ID: {}", dto.getUserId());

        Map<String, String> state = new HashMap<>();
        // 构建state对象
        Map<String, String> fusionData = fusionDataBuilder.buildFusionState(
                dto.getUserId(),
                dto.getProductDesc(),
                dto.getReferenceScriptIds());

        // 添加话术大纲到state
        state.put("script_outline", dto.getScriptOutline());
        // 添加当前选择的文本到state
        state.put("current_selection", dto.getCurrentSelection());
        // 添加当前内容到state
        if (dto.getCurrentContent() != null) {
            state.put("current_content", dto.getCurrentContent());
        }
        // 添加用户生成的特殊要求到state（如果有）
        if (dto.getUserGeneratedRequest() != null && !dto.getUserGeneratedRequest().isEmpty()) {
            state.put("user_generated_request", dto.getUserGeneratedRequest());
        }
        // 直接获取fusion_data中的JSON字符串
        state.put("fusion_data", fusionData.get("fusion_data"));

        // 构建智能体所需的payload
        Payload payload = Payload.builder()
                .agentId(agentClient.getAgentId())
                .userChatInput("根据当前选择的内容生成片段话术")
                .state(state)
                .build();

        String generatedContent;
        try {
            // 日志记录请求参数
            log.info("[ScriptFragments] 请求payload: {}", payload);
            // 调用智能体同步接口获取处理结果
            generatedContent = agentClient.chat_completions(payload);
            // 日志记录返回结果
            log.info("[ScriptFragments] 智能体返回: {}", generatedContent);
            return generatedContent;
        } catch (Exception e) {
            // 记录异常信息并抛出运行时异常
            log.error("[ScriptFragments] 智能体调用异常: {}", e.getMessage(), e);
            throw new RuntimeException("生成片段话术内容失败", e);
        }
    }
}